/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.cip.esymons.tramite.bc;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.cip.esymons.tramite.be.DocumentoExterno;

/**
 *
 * @author Administrador
 */
@Stateless
public class DocumentoExternoFacade implements DocumentoExternoFacadeLocal {
    @PersistenceContext
    private EntityManager em;

    public void create(DocumentoExterno documentoExterno) {
        em.persist(documentoExterno);
    }

    public void edit(DocumentoExterno documentoExterno) {
        em.merge(documentoExterno);
    }

    public void remove(DocumentoExterno documentoExterno) {
        em.remove(em.merge(documentoExterno));
    }

    public DocumentoExterno find(Object id) {
        return em.find(DocumentoExterno.class, id);
    }

    public List<DocumentoExterno> findAll() {
        return em.createQuery("select object(o) from DocumentoExterno as o").getResultList();
    }

    public DocumentoExterno buscarPorSerie(String serie) {
        try{
            return (DocumentoExterno)em.createQuery("select object(o) from DocumentoExterno as o Where o.docSerie = ?1").setParameter(1, serie).getSingleResult();
        }catch(NoResultException e){
            return null;
        }
        
    }

    public List<DocumentoExterno> listarXEstado(Long id) {
        try {
            Query q = null;
            StringBuilder sb = new StringBuilder();
            sb.append(" select de from Transaccion t, Operacion o, DocumentoIncluido di,");
            sb.append(" DocumentoExterno de where t = o.fkTraCodigo and o = di.fkOpeCodigo");
            sb.append(" and di.fkDocCodigo = de and t.traCodigo=?1 and o.opeEstado=0");
                        
            q = em.createQuery(sb.toString());

            q.setParameter(1, id);            

            return q.getResultList();
        } catch (Exception ex) {
            return null;
        }
    }

}
